package com.dirox.jira.notes.action;

import com.atlassian.jira.rest.api.util.ErrorCollection;
import com.atlassian.jira.security.JiraAuthenticationContext;
import com.atlassian.jira.security.xsrf.RequiresXsrfCheck;
import com.atlassian.jira.web.action.JiraWebActionSupport;
import com.atlassian.plugins.rest.common.json.DefaultJaxbJsonMarshaller;
import com.atlassian.plugins.rest.common.json.JaxbJsonMarshaller;
import com.dirox.jira.notes.entities.Note;
import com.dirox.jira.notes.service.NoteService;
import com.dirox.jira.notes.utils.ActivityHelper;
import static com.google.common.base.Preconditions.checkNotNull;
import org.apache.commons.lang.StringUtils;
import webwork.action.ActionContext;
import java.util.Hashtable;


public class DeleteNote extends JiraWebActionSupport {
	private static final long serialVersionUID = 1L;
	public static String APPLICATION_NAME_CREATED_NOTE = "JIRA Created Note";
	public static String APPLICATION_NAME_UPDATED_NOTE = "JIRA Updated Note";
	public static String APPLICATION_NAME_DELETED_NOTE = "JIRA Deleted Note";
	public static String APPLICATION_NAME_TAGGED_ISSUE = "JIRA Tagged Issue Note";
	public static String APPLICATION_NAME_TAGGED_USER = "JIRA Tagged User Note";
	private NoteService noteService;
	private ErrorCollection errors;
	private Hashtable<String, Object> responseJson;
	private String noteId;
	private ActivityHelper activityHelper;
	private JiraAuthenticationContext context;

	/**
	 * This method is execute action to create new note
	 *
	 * @return JSON content
	 */
	@RequiresXsrfCheck
	protected String doExecute() throws Exception {
		// validate the input parameters
		if (!validateInput()) {
			return ERROR;
		}

		ActionContext.getResponse()
		             .setContentType("application/json");

		// delete note
		noteService.delete(Integer.parseInt(noteId));

		// post an activity
		String title = context.getI18nHelper()
		                      .getText("notes.text.user.deleted.note")
		                      .replaceAll(
			"%user%",
			context.getLoggedInUser().getDisplayName());
		activityHelper.postActivitity(APPLICATION_NAME_DELETED_NOTE, title, "");

		this.responseJson = new Hashtable<String, Object>();
		this.responseJson.put("response",
		                      getText("notes.code.success"));
		this.responseJson.put("success", true);

		return "json";
	}

	/**
	 * Validate the input parameters
	 *
	 * @return true if validating input success, else return false
	 */
	private boolean validateInput() {
		// check if note id is not an integer number
		if (StringUtils.isBlank(noteId) || !isInteger(noteId)) {
			this.errors = ErrorCollection.of(
				getText("notes.error.note.id.must.be.integer"));

			return false;
		}

		// check if note does not exist
		if (noteService.getNote(Integer.parseInt(noteId)) == null) {
			this.errors = ErrorCollection.of(
				getText("notes.error.not.exist.note"));

			return false;
		}

		// check if currentUser is not owner
		Note note = noteService.getNote(Integer.parseInt(noteId));

		if (!getLoggedInUser()
			         .getName()
			         .equals(note.getOwner().getUserName())) {
			this.errors = ErrorCollection.of(
				getText("notes.error.not.owner.user"));

			return false;
		}

		return true;
	}

	private boolean isInteger(String s) {
		try {
			Integer.parseInt(s);
		} catch (NumberFormatException e) {
			return false;
		}

		return true;
	}

	public String getResponseJson() {
		final JaxbJsonMarshaller marshaller = new DefaultJaxbJsonMarshaller();

		return marshaller.marshal(this.responseJson);
	}

	public String getErrorJson() {
		final JaxbJsonMarshaller marshaller = new DefaultJaxbJsonMarshaller();
		this.responseJson = new Hashtable<String, Object>();
		this.responseJson.put("response", errors);
		this.responseJson.put("success", false);

		return marshaller.marshal(this.responseJson);
	}

	public void setId(String id) {
		this.noteId = id;
	}

	public void setNoteService(NoteService noteService) {
		this.noteService = checkNotNull(noteService);
	}

	public void setActivityHelper(ActivityHelper activityHelper) {
		this.activityHelper = activityHelper;
	}

	public void setContext(JiraAuthenticationContext context) {
		this.context = context;
	}
}
